package com.mall.appcontroller;

import com.domain.Buns;
import com.domain.result.ResultData;
import com.service.seinterface.BunsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/appmall")
public class AppBunsConstroller {

    @Autowired
    BunsService bunsService;


    @RequestMapping("/addBuns")
    public ResultData addBuns(Buns buns,MultipartFile file){

        return bunsService.addBuns(buns,file);
    }


    @RequestMapping("/deleteBunsById")
    public ResultData deleteBunsById(Integer bunsid){
        return bunsService.deleteBunsById(bunsid);
    }


    @RequestMapping("/updateBunsById")
    public ResultData updateBunsById(Buns buns,MultipartFile file){
        return bunsService.updateBunsById(buns,file);
    }

    @RequestMapping("/selectBunsAll")
    public ResultData selectBunsAll(){
        return bunsService.selectBunsAll();
    }


    @Value(value = "${file.location}")
    public String filepathdir;
    @RequestMapping(value = "/downloadFile/{filepath}", method = RequestMethod.GET)
    public void downloadFile(@PathVariable(value = "filepath")String filepath,HttpServletResponse res)
            throws IOException {

        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + filepath);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filepathdir,filepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }


}
